import MyUpload from '@/components/MyUpload';
import {
  createProduct,
  deleteProduct,
  getProductAttributeList,
  getProductCategory,
  getProductDetail,
  getProductList,
  updateProduct,
} from '@/services/ant-design-pro/product';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormDigit,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
  ProTable,
  useDebounceFn,
} from '@ant-design/pro-components';
import { FormattedMessage, useNavigate } from '@umijs/max';
import {
  Button,
  Card,
  Col,
  Drawer,
  Form,
  Input,
  message,
  Popconfirm,
  Row,
  Select,
  Tag,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import Zoom from 'react-medium-image-zoom';

const TableList: React.FC = () => {
  const [dataSource, setDataSource] = useState([]);
  const [collectionOptions, setCollectionOptions] = useState([]);
  const [skuOptions, setSkuOptions] = useState([]);
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  const [currentSkuItem, setCurrentSkuItem] = useState(null);
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [searchParams, setSearchParams] = useState({});

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();

  const nav = useNavigate();

  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: API.RuleListItem) => {
    const hide = message.loading('正在添加');
    try {
      const data = { status: 1, ...fields };

      if (data?.variants) {
        data.variants = data?.variants.map((item) => {
          return { ...item, price: Number(item.price), stock: Number(item.stock) };
        });
      }

      if (currentSkuItem)
        data.attributesValue = [
          {
            id: currentSkuItem?.id,
            values: currentSkuItem?.attributeValues?.map((item) => item.id),
          },
        ];

      const resp = await await createProduct(data);
      hide();
      if (resp?.code === 1) {
        return;
      }
      message.success('添加成功');
      return true;
    } catch (error) {
      hide();
      message.error('添加失败，请重试。');
      return false;
    }
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: FormValueType) => {
    const hide = message.loading('更新中');
    try {
      const data = { status: 1, ...fields };
      console.log('[data]', currentSkuItem);
      if (data?.variants?.length > 0)
        data.attributesValue = [
          {
            id: currentSkuItem?.id,
            values: data?.variants?.map((item) => item?.attValues?.[0]),
          },
        ];

      if (data?.variants) {
        data.variants = data?.variants.map((item) => {
          return { ...item, price: Number(item.price), stock: Number(item.stock) };
        });
      }

      const resp = await updateProduct(data);
      hide();
      if (resp?.code === 1) {
        return;
      }
      message.success('编辑成功');
      return true;
    } catch (error) {
      hide();
      message.error('编辑失败');
      return false;
    }
  };

  const SkuItems = ({ value, onChange }) => {
    return (
      <div>
        <Select
          options={skuOptions}
          value={currentSkuItem?.id}
          onChange={(value) => {
            setCurrentSkuItem(skuOptions?.find((item) => item.value === value)?.item);
          }}
        ></Select>

        <Row gutter={16} style={{ marginTop: 16 }}>
          {(currentSkuItem?.values || currentSkuItem?.attributeValues)?.map((item, index) => {
            return (
              <Col span={12} key={item.id}>
                <Card title={item.value || item.label} size="small">
                  <Form.Item label={`id`} name={['variants', index, 'id']} hidden>
                    <Input></Input>
                  </Form.Item>
                  <Form.Item
                    rules={[
                      {
                        required: true,
                      },
                    ]}
                    label={`价格`}
                    name={['variants', index, 'price']}
                  >
                    <Input type="number"></Input>
                  </Form.Item>
                  <Form.Item
                    rules={[
                      {
                        required: true,
                      },
                    ]}
                    label={'库存'}
                    name={['variants', index, 'stock']}
                  >
                    <Input type="number"></Input>
                  </Form.Item>

                  <Form.Item
                    label={'依赖SKU'}
                    hidden
                    initialValue={[item.id]}
                    name={['variants', index, 'attValues']}
                  >
                    <Input></Input>
                  </Form.Item>
                  <Form.Item
                    label={'状态'}
                    hidden
                    initialValue={1}
                    name={['variants', index, 'status']}
                  >
                    <Input></Input>
                  </Form.Item>
                </Card>
              </Col>
            );
          })}
        </Row>
      </div>
    );
  };

  const handleShelf = async (record) => {
    const detailResp = await getProductDetail(record.id);
    const data = detailResp?.data;

    const body = { ...data, categoryId: record?.category?.id };

    const skuItem = { ...data?.attributeGroups?.[0] };
    if (body?.variants?.length > 0)
      body.attributesValue = [
        {
          id: skuItem?.id,
          values: body?.variants?.map((item) => item?.attributeValues?.[0]),
        },
      ];

    if (body?.variants) {
      body.variants = body?.variants.map((item) => {
        return {
          ...item,
          price: Number(item.price),
          stock: Number(item.stock),
          attValues: item?.attributeValues?.map((item) => item?.id),
        };
      });
    }

    const resp = await updateProduct(body);
    if (resp?.code === 1) {
      return;
    }
    message.success('编辑成功');
    return true;
  };

  const columns: ProColumns<API.RuleListItem>[] = [
    {
      search: false,
      title: '名称',
      dataIndex: 'title',
      width: 150,
    },
    {
      search: false,
      title: '分类',
      dataIndex: 'category',
      width: 80,
      render: (data) => {
        return data?.name;
      },
    },
    {
      search: false,
      title: '标签',
      dataIndex: 'tagList',
      render: (data) => {
        if (data?.length > 0) {
          return data?.map((item) => <Tag key={item?.id} color="blue">{item?.name}</Tag>);
        }
        return '-';
      },
    },
    {
      search: false,
      title: '图片',
      dataIndex: 'image',
      render: (data, record) => {
        if (record.image) {
          return (
            <Zoom>
              <img
                src={data}
                style={{ width: '80px', objectFit: 'contain', height: '40px' }}
                alt=""
              />
            </Zoom>
          );
        } else {
          return <span style={{ color: '#999' }}>暂无图片</span>;
        }
      },
    },
    {
      search: false,
      title: '价格',
      dataIndex: 'price',
      render: (price, record) => {
        if (record.attributeGroups?.length > 0 && record.variants?.length > 0) {
          const prices = record.variants.map(item => Number(item.price));
          const minPrice = Math.min(...prices);
          const maxPrice = Math.max(...prices);
          
          if (minPrice === maxPrice) {
            return `¥${minPrice.toFixed(2)}`;
          }
          return `¥${minPrice.toFixed(2)} ~ ¥${maxPrice.toFixed(2)}`;
        } 
        else {
          return price ? `¥${Number(price).toFixed(2)}` : '-';
        }
      },
    },
    {
      search: false,
      title: '上下架',
      dataIndex: 'status',
      render: (data) => {
        if (data) return <Tag color="blue">上架</Tag>;
        return <Tag color="red">下架</Tag>;
      },
    },
    {
      search: false,
      title: '是否可购买',
      dataIndex: 'canBuy',
      valueType: 'textarea',
      render: (data) => {
        if (data) return <Tag color="blue">可购买</Tag>;
        return <Tag color="red">仅展示</Tag>;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            nav(`/product/detail/${record.id}`);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          title="确认删除吗"
          key="delete"
          onConfirm={async () => {
            await deleteProduct(record.id);
            init();
          }}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const initCollection = async () => {
    const resp = await getProductCategory();

    const { list } = resp?.data;
    const options = list.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
    setCollectionOptions(options);
  };

  const initSKU = async () => {
    const resp = await getProductAttributeList();

    const { list } = resp?.data;
    const options = list.map((item) => {
      return {
        label: item.name,
        value: item.id,
        item,
      };
    });
    setSkuOptions(options);
  };

  const init = async (params = {}) => {
    const resp = await getProductList({ ...params, page: 1, pageSize: 50 });

    const { list } = resp?.data;
    setDataSource(list);
  };

  const { run: handleSearch } = useDebounceFn((params) => {
    setSearchParams({ ...searchParams, ...params });
    return init({ ...searchParams, ...params });
  }, 500);

  useEffect(() => {
    initCollection();

    initSKU();

    init();
  }, []);

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        actionRef={actionRef}
        rowKey="key"
        search={false}
        toolbar={{
          search: (
            <Row gutter={10}>
              <Col>
                <Input
                  placeholder="请输入商品名称"
                  onChange={(e) => {
                    handleSearch({
                      keyword: e.target.value,
                    });
                  }}
                ></Input>
              </Col>
              <Col>
                <Select
                  style={{ width: '170px' }}
                  options={collectionOptions}
                  allowClear
                  onChange={(value) => {
                    handleSearch({
                      category: value,
                    });
                  }}
                  placeholder="可筛选商品分类"
                ></Select>
              </Col>
              <Col>
                <Select
                  style={{ width: '170px' }}
                  options={[
                    {
                      label: '上架',
                      value: 1,
                    },
                    {
                      label: '下架',
                      value: 0,
                    },
                  ]}
                  allowClear
                  onChange={(value) => {
                    handleSearch({
                      status: value,
                    });
                  }}
                  placeholder="可筛选上下架"
                ></Select>
              </Col>
            </Row>
          ),
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              nav('/product/detail/new');
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        dataSource={dataSource}
        columns={columns}
        onLoad={init}
        options={false}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
